﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyWeb.ServiceBus.Common;
using MyWeb.ServiceBus.Model;
using MyWeb.ServiceBus.Model.Models;
using MyWeb.ServiceBus.Services;
using MyWeb.ServiceBus.Services.Db;
using Nacos.V2.Utils;
using System;

namespace MyWeb.ServiceBus.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InterfaceController : ControllerBase
    {
        private readonly IInterfaceService service;
        private readonly Context db;
        public InterfaceController(IInterfaceService interfaceService,Context context)
        {
            service = interfaceService;
            db = context;
        }

        [HttpGet]
        public ApiResult Get()
        {
            var data = service.Query(i=> 1 == 1);

            return ApiResult.SUCCESS(data);
        }
        [HttpGet]
        public ApiResult GetPage(long appId,int page,int pageSize)
        {
            var data = service.QueryPage(i => i.ApplicationId == appId, out long count, page, pageSize);
            PageModel res = new(page,(int)count,pageSize,data);

            return ApiResult.SUCCESS(res);
        }

        [HttpPost]
        public ApiResult Add(Interface @interface)
        {
            if(@interface.ApplicationId <= 0)
            {
                return ApiResult.FAILED("请先选择项目");
            }
            if(@interface.Name.IsNullOrWhiteSpace())
            {
                return ApiResult.FAILED("接口名称不允许为空！");
            }
            if (@interface.Path.IsNullOrWhiteSpace())
            {
                return ApiResult.FAILED("接口地址不正确!");
            }
            @interface.Id = Snowflake.NextId();
            if (service.Add(@interface) <= 0)
            {
                return ApiResult.FAILED("保存失败!");
            }

            return ApiResult.SUCCESS();
        }

        [HttpPut]
        public async Task<ApiResult> Edit(Interface @interface)
        {
            if (@interface.Id <= 0)
            {
                return ApiResult.FAILED("请正确选择接口！");
            }
            if (@interface.ApplicationId <= 0)
            {
                return ApiResult.FAILED("请先选择项目");
            }
            if (@interface.Name.IsNullOrWhiteSpace())
            {
                return ApiResult.FAILED("接口名称不允许为空！");
            }
            if (@interface.Path.IsNullOrWhiteSpace())
            {
                return ApiResult.FAILED("接口地址不正确!");
            }

            var data = (await service.QueryAsync(i => i.Id == @interface.Id)).Single();

            data.Name = @interface.Name;
            data.Path = @interface.Path;
            data.Status = @interface.Status;
            data.Method = @interface.Method;
            data.Classification = @interface.Classification;
            data.Remark = @interface.Remark;
            data.UpdateDate = DateTime.Now;
            data.UpdateUserId = 1;

            if (service.Edit(data) <= 0)
            {
                return ApiResult.FAILED("保存失败！");
            }

            return ApiResult.SUCCESS();
        }

        [HttpPost]
        public async Task<ApiResult> schema2json(List<InterDoc> doc)
        {
            return ApiResult.SUCCESS(dynamic2Json(doc,null));
        }

        private object dynamic2Json(List<InterDoc> doc, InterDoc pDoc)
        {
            Dictionary<string, object> keys = new Dictionary<string, object>();


            Random random = new Random();
            string characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // 可选的字符集
            int length = 10; // 字符串长度
            string fieId = "";

            foreach (var item in doc)
            {
                fieId = item.field;
                if (pDoc is not null && pDoc.parType.Equals("array"))
                {
                    fieId = "";
                    switch (item.parType)
                    {
                        case "array":
                            return new List<object>(){dynamic2Json(item.child,item)};
                            break;
                        case "object":
                            return dynamic2Json(item.child, item);
                            break;
                        case "number":
                            return random.NextDouble();
                            break;
                        case "boolean":
                            return Convert.ToBoolean(random.Next(2));
                            break;
                        case "integer":
                            return random.NextInt64();
                            break;
                        default:
                            //生成随机字符串
                            return new string(Enumerable.Repeat(characters, length)
                                                          .Select(s => s[random.Next(s.Length)])
                                                          .ToArray());
                            break;
                    }

                }
                switch (item.parType)
                {
                    case "array":
                        keys.Add(fieId, new List<object>()
                        {
                            dynamic2Json(item.child,item)
                        });
                        break;
                    case "object":
                        keys.Add(fieId, dynamic2Json(item.child,item));
                        break;
                    case "number":
                        keys.Add(fieId, random.NextDouble());
                        break;
                    case "boolean":
                        keys.Add(fieId, Convert.ToBoolean(random.Next(2)));
                        break;
                    case "integer":
                        keys.Add(fieId, random.NextInt64());
                        break;
                    default:
                        //生成随机字符串
                        keys.Add(fieId, new string(Enumerable.Repeat(characters, length)
                                                      .Select(s => s[random.Next(s.Length)])
                                                      .ToArray()));
                        break;
                }
            }
            return keys;
        }

        public class InterDoc
        {
            /// <summary>
            /// Id
            /// </summary>
            public long Id { get; set; }
            /// <summary>
            /// 是否必须
            /// </summary>
            public bool isExpand { get; set; }
            /// <summary>
            /// 字段名称
            /// </summary>
            public string field { get; set; }
            //public bool isFinite { get; set; }
            /// <summary>
            /// 字段类型
            /// </summary>
            public string parType { get; set; }
            /// <summary>
            /// mock参数
            /// </summary>
            public string mock { get; set; }
            /// <summary>
            /// 字段描述
            /// </summary>
            public string description { get; set; }
            /// <summary>
            /// 父级Id
            /// </summary>
            public long parentId { get; set; }
            /// <summary>
            /// 子项
            /// </summary>
            public List<InterDoc> child { get; set; }
        }
    }
}
